<?php
$auth = Auth::getAuth('current_user');
$db = new Database();
$fs = new functions();
$userCompany = new userQueries();
$upload = new upload();
$post = new post();
$noti = new notifications();
$mail = new Mail_Notification();
if(Auth::hasAuth('current_user')){
    if(isset($_POST['action'])){
        
        $action = $_POST['action'];
        $date = $fs->currentDateTime();
        
            // Save created post to the database
            if($action=="createPost"){
                // $getpost = strip_tags($_POST['cPost'], '<a>');
                $getpost = $_POST['cPost'];
                $getAllHashTag = $_POST['getAllHashTag'];
                $getAllTag = $_POST['getAllTag'];
                $images = $_POST['imagesGet'];
                $type = $_POST['type'];
                $postPrivacyType = $_POST['postPrivacyType'];
                $postPrivacyIDs = $_POST['postPrivacyIDs'];
                    $decode_img = json_decode($images,true);
                // Save created post
                    $postID = $post->createPost($getpost,$auth,$type,$postPrivacyType,$postPrivacyIDs);
                
                // Save Hashtag
                    $get_hashtag = explode(",",$getAllHashTag);
                    foreach($get_hashtag as $hashTag){
                        $insert = array("hashtag"   =>      $hashTag,
                                        "post_id"   =>      $postID,      
                                        "type"      =>      "0",
                                        "user"      =>      $auth['id'],
                                        "date"      =>      "",
                                        "is_active" =>      "1");
                        $db->insert("tbhashtag",$insert);
                    }
		    
		    // Save notificaion INsert notification
		    $noti->inserNotification("post","tbpost",$auth,$postID,$getAllTag);
                    
                
                // Create folder for the postImage
		    $folder_name = $_POST['folder_location'];
                    $path = "images/" . $folder_name;
                    $id_encrypt = md5(md5($postID));
		    $dir = $path."/".$id_encrypt;
		    if(count($decode_img)!=0){  
                        $upload->createFolder($dir);
		    }
                        // Move files to the directory
                        $copy_foldername = md5(md5($auth['id']));
			$from = "images/" . $folder_name . "/temporaray_files/".$copy_foldername;
                        $postFiles = $upload->getAllfiles_fromDirectory($from);
                            $ext_file = array();
			    $ext_img = array();
                                foreach($decode_img as $img){
                                    copy($from . '/' . $img, $dir . '/' . $img);
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
                            $upload->unlinkRecursive($from, "");
                    
                    // Return        
                    $postImage = $upload->getAllfiles_fromDirectory($dir);
                    
                    // 
                        $encodePostImage = array(   "img"                   =>  $decode_img,
                                                    "postFolderName"        =>  $id_encrypt,
                                                    "lengthImg"             =>  count($ext_img),
						    "extension_file"	    =>  $ext_file,
						    "extension_img"	    =>  $ext_img,
						    "FolderName" 	    => $folder_name,
						    "image_resize"	=>	getimagesize($path_resize_image));
                       
                // Return Post
                    $encodePost = array("post"                          =>      $post->returnPost($auth,$getpost,$encodePostImage,$postID,"","return",$postPrivacyType),
                                        "uploadedImages"                =>      $encodePostImage);
                
                    $arr[] = array('getpost'=>$encodePost);
                    echo json_encode($arr);
		    
		    if($getAllTag!=""){
			$db_get_query = $db->query("SELECT * FROM tbuser WHERE id IN ($getAllTag) AND is_active='1'","array");
			foreach($db_get_query as $info_u){
			    $json_decode = Settings::noti_settings($info_u['id'],'notifications');
			    $json_notifications = $json_decode[0]['notifications'];
			    $json_n = $json_notifications['Tagged'];
			    $m = "post";
			    $path = functions::curPageURL('port') . "/index?type=go&redirect=post?view_type=view_post|=%=|postID=" . functions::base_encode_decode("encrypt",$postID);
			    if($json_n[0]=="1"){
				$mail = new Mail_Notification();
				$img = $userCompany->avatarPic("tbuser",$auth['id'],"60","60","small","avatar",'style="float: left;border-radius:50px;margin-right: 5px;"');
				$name = $auth['first_name'] . " " . $auth['last_name'];
				$f_name = $auth['first_name'];
				$mail->set_notifications(array($info_u['email']=>$info_u['display_name']),$getpost,$img,$auth['id'],$name,"tagged you in a post",$f_name,$m,"comment",$path);
			    }
			}
		    }
            }
            
            // Load create post
            elseif($action=="loadPost"){
            /*
             * Load Post from the Database accordin to their company
             */
                $getPost = $db->query("SELECT *,p.id as postID  FROM tbpost p
                                      LEFT JOIN tbuser u on p.postedBy=u.id
                                      WHERE p.is_active={$db->escape(1)}
                                    AND (
                                            CASE 
                                            WHEN p.postPrivacyType = 1 THEN
                                                EXISTS (SELECT * FROM (select g.id from tbgroups g WHERE g.id IN
                                                (SELECT 
                                                 CASE 
                                                 WHEN FIND_IN_SET(u.id, g.Members)>0
                                                 THEN g.id
                                                 ELSE ''
                                                 END
                                                 FROM tbuser u WHERE u.id={$auth['id']})) A
                                                WHERE A.id IN (SELECT 
                                                CASE WHEN FIND_IN_SET(A.ID, p1.postPrivacyIDs)>0 THEN
                                                  A.id
                                                ELSE 
                                                  ''
                                                END               
                                                FROM tbpost p1 WHERE p1.ID = p.id))
                                            WHEN p.postPrivacyType = 2 THEN
                                                FIND_IN_SET({$db->escape($auth['department_id'])},p.postPrivacyIDs)
                                            WHEN p.postPrivacyType = 3 THEN
                                                FIND_IN_SET({$db->escape($auth['position'])},p.postPrivacyIDs)
                                            else
                                                u.company_id={$db->escape($auth['company_id'])}
                                           END
                                            )
                                    OR u.id = {$db->escape($auth['id'])} 
                                      ORDER BY date_updated DESC 
                      LIMIT 20","array");
                
                foreach ($getPost as $dataP){
                    
                    $path = "images/postUpload";
                    $id_encrypt = md5(md5($dataP['postID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
                        $encodePostImage = array("img"            =>  $postFiles,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
						    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                   
                   
                    
                    // LOAD POST DETAILS RETURN
                    $encodePost = array("post"                  =>      $post->returnPost($auth,$getpost,$encodePostImage,$dataP['postID'],$dataP,"query"),
                                        
                                        "uploadedImages"        =>      $encodePostImage);
                    
                    
                    //,'getcomment'=>$encodeComment,'getLike'=>$encodeLike,'getLikeComment'=>$encodeLikeComment
                     
                    $arr[] = array("getpost"            =>      $encodePost,
                                   "getcomment"         =>      $post->loadCommentPost($auth,$dataP['postID'],"","5"),
                                   "getLike"            =>      $post->loadLike($auth,$dataP['postID'],"post"));
                }
                echo functions::view_json_formatter(json_encode($arr));
                
            }
            
            // Show LoadMore results
            elseif($action=="loadText"){
                $id = $_POST['id'];
                $actionType = $_POST['actionType'];
                if($actionType=="post"){
                    $getText = $db->query("SELECT * FROM tbpost WHERE id={$db->escape($id)} AND is_active={$db->escape(1)}","row");
                    echo htmlspecialchars_decode($getText['post']);
                }else{
                    $getText = $db->query("SELECT * FROM tbcomment WHERE id={$db->escape($id)} AND is_active={$db->escape(1)}","row");
                    echo htmlspecialchars_decode($getText['comment']);
                }
                
            }
            
            // Delete record from the database
            elseif($action=="delete"){
                $delAction = $_POST['delAction'];
                $postID = $_POST['postID'];
                    $post->deletion($delAction,$postID);
            }
            
            // Create Reply
            elseif($action=="createReply"){
                $postID = $_POST['postID'];
                $type = $_POST['type'];
                $comment = $_POST['reply'];
                $fID = $_POST['fID'];
		$images = $_POST['imagesGet'];
		    $decode_img = json_decode($images,true);
		$folder_name = $_POST['folder_location'];
		$getAllTag = $_POST['getAllTag'];
		
		    
		    
		    $arr[] = array("returnComment"      =>      $post->createComment($comment,$type,$postID,$auth,$fID,$decode_img,$folder_name),
                                   "getcomment"         =>      $post->loadCommentPost($auth,$postID,"","5"),
                                   "getLike"            =>      $post->loadLike($auth,$postID,"post"),
                                   "getNoti"            =>      $noti->inserNotification("comment","tbpost",$auth,array("postID"=>$postID,"comment"=>$comment),$getAllTag));
                    
		    
                    echo json_encode($arr);
		    
		    // INsert notification
                    // 2014 03 04 - removed duplicate insert notification, the 
                    // function call above is enough.
//		    $noti->inserNotification("comment","tbpost",$auth,array("postID"=>$postID,"comment"=>$comment),$getAllTag);

		    
            }
            
            // Like Post
            elseif($action=="like"){
                $postID = $_POST['postID'];
                $likeAction = $_POST['likeAction'];
                $likeType = $_POST['likeType'];
                $likeID = $_POST['likeID'];
                echo $post->likes_unlike($auth,$postID,$likeAction,$likeType,$likeID);
            }
            
            // Load More
            elseif($action=="loadMore"){
                $lastID = $_POST['lastID'];
                /*
                *
                *
                */
                   $getPost = $db->query("SELECT *,p.id as postID  FROM tbpost p
                                         LEFT JOIN tbuser u on p.postedBy=u.id
                                         WHERE p.date_updated <{$db->escape($lastID)} AND p.is_active={$db->escape(1)}
                                         AND u.company_id={$db->escape($auth['company_id'])}
                                         ORDER BY p.date_updated DESC LIMIT 5","array");
//		    $getPost = $db->query("SELECT *,p.id as postID  FROM tbpost p
//                                      LEFT JOIN tbuser u on p.postedBy=u.id
//                                      WHERE p.is_active={$db->escape(1)} AND date_updated <{$db->escape($lastID)}
//                                    AND (
//                                            CASE 
//                                            WHEN p.postPrivacyType = 1 THEN
//                                                EXISTS (SELECT * FROM (select g.id from tbgroups g WHERE g.id IN
//                                                (SELECT 
//                                                 CASE 
//                                                 WHEN FIND_IN_SET(u.id, g.Members)>0
//                                                 THEN g.id
//                                                 ELSE ''
//                                                 END
//                                                 FROM tbuser u WHERE u.id={$auth['id']})) A
//                                                WHERE A.id IN (SELECT 
//                                                CASE WHEN FIND_IN_SET(A.ID, p1.postPrivacyIDs)>0 THEN
//                                                  A.id
//                                                ELSE 
//                                                  ''
//                                                END               
//                                                FROM tbpost p1 WHERE p1.ID = p.id))
//                                            WHEN p.postPrivacyType = 2 THEN
//                                                FIND_IN_SET({$db->escape($auth['department_id'])},p.postPrivacyIDs)
//                                            WHEN p.postPrivacyType = 3 THEN
//                                                FIND_IN_SET({$db->escape($auth['position'])},p.postPrivacyIDs)
//                                            else
//                                                u.company_id={$db->escape($auth['company_id'])}
//                                           END
//                                            )
//                                    OR u.id = {$db->escape($auth['id'])} 
//                                      ORDER BY date_updated DESC  LIMIT 5","array");  
                   
		   
                foreach ($getPost as $dataP){
                    
                    $path = "images/postUpload";
                    $id_encrypt = md5(md5($dataP['postID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
                    //
		    $encodePostImage = array("img"            =>  $postFiles,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
						    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                   
                   
                    
                    // LOAD POST DETAILS RETURN
                    $encodePost = array("post"                  =>      $post->returnPost($auth,$getpost,$encodePostImage,$dataP['postID'],$dataP,"query"),
                                        
                                        "uploadedImages"        =>      $encodePostImage);
                    
                    
                    //,'getcomment'=>$encodeComment,'getLike'=>$encodeLike,'getLikeComment'=>$encodeLikeComment
                     
                    $arr[] = array("getpost"            =>      $encodePost,
                                   "getcomment"         =>      $post->loadCommentPost($auth,$dataP['postID'],"","5"),
                                   "getLike"            =>      $post->loadLike($auth,$dataP['postID'],"post"));
                }
                echo functions::view_json_formatter(json_encode($arr));
            }
            
            // Load More Comment
            elseif($action=="loadComment"){
                $lastID = $_POST['lastID'];
                $postID = $_POST['postID'];
                
                         $arr[] = array('getcomment'=>$post->loadCommentPost($auth,$postID," c.id<{$db->escape($lastID)} AND ",""));
       
                       echo json_encode($arr);
                       
            }
            
            // Get Comment
            elseif($action=="getComment"){
                $postID = $_POST['postID'];
                $formID = $_POST['formID'];
                echo json_encode($post->get_comment($auth,$postID,"1","",$formID));
            }
            
            // Get HashTag
            elseif($action=="getHashTag"){
                $getHashTag = "#" . $_POST['data_hashTag'];
                $get_hashTag = $db->query("SELECT *,p.id as postID FROM tbhashtag h
                                          LEFT JOIN tbuser u on h.user=u.id
                                          LEFT JOIN tbpost p on h.post_id=p.id
                                          WHERE p.is_active={$db->escape(1)}
                                          AND u.company_id={$db->escape($auth['company_id'])}
                                          AND h.hashtag={$db->escape($getHashTag)}
                                          ORDER BY p.id DESC LIMIT 20
                                          ","array");
                //$get_hashTag = $db->query("SELECT *,p.id as postID  FROM tbpost p
                //                      LEFT JOIN tbuser u on p.postedBy=u.id
                //                      LEFT JOIN tbhashtag h on p.id=h.post_id
                //                      WHERE p.is_active={$db->escape(1)}
                //                      AND u.company_id={$db->escape($auth['company_id'])}
                //                      AND h.post_id={$db->escape($getHashTag)}
                //                      ORDER BY p.id DESC LIMIT 20","array");
                
                foreach($get_hashTag as $hashTag){
                    $path = "images/postUpload";
                    $id_encrypt = md5(md5($hashTag['postID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
                    //
                        $encodePostImage = array("img"            =>  $postFiles,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
						    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                        
                    // LOAD POST DETAILS RETURN
                    $encodePost = array("post"                  =>      $post->returnPost($auth,"",$encodePostImage,$hashTag['postID'],$hashTag,"query"),
                                        "uploadedImages"        =>      $encodePostImage);
                    
                    
                    //,'getcomment'=>$encodeComment,'getLike'=>$encodeLike,'getLikeComment'=>$encodeLikeComment
                     
                    $return[] = array("getpost"            =>      $encodePost,
                                   "getcomment"         =>      $post->loadCommentPost($auth,$hashTag['postID'],"","5"),
                                   "getLike"            =>      $post->loadLike($auth,$hashTag['postID'],"post"),
                                   "hashTag"=>$getHashTag);
                }
                echo json_encode($return);
            }
	     
	    elseif($action=="selected_post"){
		$postID = $this->base_encode_decode("decrypt",$_POST['postID']);
		
		/*
             * Load Post from the Database accordin to their company
             */
                $getPost = $db->query("SELECT *,p.id as postID  FROM tbpost p
                                      LEFT JOIN tbuser u on p.postedBy=u.id
                                      WHERE p.is_active={$db->escape(1)} AND
				      p.id={$db->escape($postID)}
                                      AND u.company_id={$db->escape($auth['company_id'])}","array");
                
                foreach ($getPost as $dataP){
                    
                    $path = "images/postUpload";
                    $id_encrypt = md5(md5($dataP['postID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
                        $encodePostImage = array("img"            =>  $postFiles,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
						    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                   
                   
                    
                    // LOAD POST DETAILS RETURN
                    $encodePost = array("post"                  =>      $post->returnPost($auth,$getpost,$encodePostImage,$dataP['postID'],$dataP,"loadSingle"),
                                        
                                        "uploadedImages"        =>      $encodePostImage);
                    
                    
                    //,'getcomment'=>$encodeComment,'getLike'=>$encodeLike,'getLikeComment'=>$encodeLikeComment
                     
                    $arr[] = array("getpost"            =>      $encodePost,
                                   "getcomment"         =>      $post->loadCommentPost($auth,$dataP['postID'],"",""),
                                   "getLike"            =>      $post->loadLike($auth,$dataP['postID'],"post"));
                }
                echo functions::view_json_formatter(json_encode($arr));



	    }else if($action=="getPrivacy"){
		$search = new Search();
		$type = $_POST['type'];
		    switch ($type) {
			case '1':
			    //get groups
			    $getAllGroups = $search->getAllGroups();
			    echo json_encode($getAllGroups);
			    break;
			case '2':
			    //get departments
			    $getAllDepartment = $search->getAllDepartment();
			    echo json_encode($getAllDepartment);
			    break;
			case '3':
			    //get positions
			    $getPosition = $search->getAllPosition();
			    echo json_encode($getPosition);
			    break;
		}

            
	    } 
	    
	    // Load Image in Modal
	    elseif($action=="loadImage"){
		$dataID = $_POST['dataID'];
		$dataName = $_POST['dataName'];
		
		    $path = "images/postUpload";
                    $id_encrypt = md5(md5($dataID));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
		    $encodePostImage = array(	"img"            	=>  	$postFiles,
						"postFolderName"     	=>  	$id_encrypt,
						"lengthImg"          	=> 	count($ext_img),
						"extension_file"	=>  	$ext_file,
						"extension_img"		=>  	$ext_img,
						"image_resize"		=>	getimagesize($path_resize_image)
					    );
		    
		    echo json_encode($encodePostImage);
	    }
	    
	    
	    // Seen Post
	    elseif($action=="seenPost"){
		$postID = $_POST['postID'];
		
		$getSeen = $db->query("SELECT * FROM tbseen WHERE seen_id={$db->escape($postID)} AND type={$db->escape(2)} AND userID={$db->escape($auth['id'])}","numrows");
		if($getSeen==0){
		    $insert = array("seen_id"		=>	$postID,
				    "type"		=>	2,
				    "userID"		=>	$auth['id'],
				    "user_read"		=>	1,
				    "date"		=>	$date,
				    "is_active"		=>	1);
		    
		    $seen_id = $db->insert("tbseen",$insert);
		    echo json_encode(array("Notification"	=>	"Successfull",
					    "Seen_ID"		=>	$seen_id));
		}
	    }
            
	    
	    // Starred Post
	    elseif($action=="starredPost"){
		$postID = $_POST['postID'];
		$addAction = $_POST['addAction'];
		if($addAction=="addStarred"){
		    $getStarred = $db->query("SELECT * FROM tbstarred WHERE user_id={$db->escape($auth['id'])} AND data_id={$db->escape($postID)} AND type={$db->escape(1)}","numrows");
		    if($getStarred==0){
			$insert = array("type"		=>	1,
					"tablename"	=>	"tbpost",
					"data_id"	=>	$postID,
					"user_id"	=>	$auth['id']);
			
			$db->insert("tbstarred",$insert);
			// Update Date Modified
			// $updatePost = array("date_updated"=>$date);
			// $whereupdatePost = array("id"=>$postID);
			// $db->update("tbpost",$updatePost,$whereupdatePost);
			// Audit Logs
			$userCompany->auditLogs($auth,"tbstarred","19",$postID);
			echo json_encode(array("starred"=>$post->get_starred($postID)));
		    }
		}else{
		    //$db->delete("tbstarred",array("data_id"=>$postID,"type"=>1)); //sam
            $db->delete("tbstarred",array("data_id"=>$postID,"type"=>1,"user_id"=>$auth['id']));
		    // Audit Logs
			$userCompany->auditLogs($auth,"tbstarred","20",$postID);
		    echo json_encode(array("starred"=>$post->get_starred($postID)));
		}
		
	    }
	    
	    // Load Company Event Post
	    elseif($action=="loadCompanyEvent"){
		/*
             * Load Post from the Database accordin to their company
             */
                $getPost = $db->query("SELECT *,p.id as postID  FROM tbpost p
                                      LEFT JOIN tbuser u on p.postedBy=u.id
                                      WHERE p.is_active={$db->escape(1)}
				      AND p.post_type={$db->escape(2)}
                                    AND (
                                            CASE 
                                            WHEN p.postPrivacyType = 1 THEN
                                                EXISTS (SELECT * FROM (select g.id from tbgroups g WHERE g.id IN
                                                (SELECT 
                                                 CASE 
                                                 WHEN FIND_IN_SET(u.id, g.Members)>0
                                                 THEN g.id
                                                 ELSE ''
                                                 END
                                                 FROM tbuser u WHERE u.id={$auth['id']})) A
                                                WHERE A.id IN (SELECT 
                                                CASE WHEN FIND_IN_SET(A.ID, p1.postPrivacyIDs)>0 THEN
                                                  A.id
                                                ELSE 
                                                  ''
                                                END               
                                                FROM tbpost p1 WHERE p1.ID = p.id))
                                            WHEN p.postPrivacyType = 2 THEN
                                                FIND_IN_SET({$db->escape($auth['department_id'])},p.postPrivacyIDs)
                                            WHEN p.postPrivacyType = 3 THEN
                                                FIND_IN_SET({$db->escape($auth['position'])},p.postPrivacyIDs)
                                            else
                                                u.company_id={$db->escape($auth['company_id'])}
                                           END
                                            )
                                    OR
				    p.is_active={$db->escape(1)}
				      AND p.post_type={$db->escape(2)}
                                    AND
				    u.id = {$db->escape($auth['id'])} 
                                      ORDER BY date_updated DESC 
                      LIMIT 5","array");
                
                foreach ($getPost as $dataP){
                    
                    $path = "images/postUpload";
                    $id_encrypt = md5(md5($dataP['postID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
                        $encodePostImage = array("img"            =>  $postFiles,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
						    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                   
                   
                    
                    // LOAD POST DETAILS RETURN
                    $encodePost = array("post"                  =>      $post->returnPost($auth,$getpost,$encodePostImage,$dataP['postID'],$dataP,"query"),
                                        
                                        "uploadedImages"        =>      $encodePostImage);
                    
                    
                    //,'getcomment'=>$encodeComment,'getLike'=>$encodeLike,'getLikeComment'=>$encodeLikeComment
                     
                    $arr[] = array("getpost"            =>      $encodePost,
                                   "getcomment"         =>      $post->loadCommentPost($auth,$dataP['postID'],"","5"),
                                   "getLike"            =>      $post->loadLike($auth,$dataP['postID'],"post"));
                }
                echo functions::view_json_formatter(json_encode($arr));
	    }
	    
	    // Load Company Event Post
	    elseif($action=="loadCompanyEventList"){
		/*
             * Load Post from the Database accordin to their company
             */
                $getPost = $db->query("SELECT *,p.id as postID  FROM tbpost p
                                      LEFT JOIN tbuser u on p.postedBy=u.id
                                      WHERE p.is_active={$db->escape(1)}
				      AND p.post_type={$db->escape(2)}
                                    AND (
                                            CASE 
                                            WHEN p.postPrivacyType = 1 THEN
                                                EXISTS (SELECT * FROM (select g.id from tbgroups g WHERE g.id IN
                                                (SELECT 
                                                 CASE 
                                                 WHEN FIND_IN_SET(u.id, g.Members)>0
                                                 THEN g.id
                                                 ELSE ''
                                                 END
                                                 FROM tbuser u WHERE u.id={$auth['id']})) A
                                                WHERE A.id IN (SELECT 
                                                CASE WHEN FIND_IN_SET(A.ID, p1.postPrivacyIDs)>0 THEN
                                                  A.id
                                                ELSE 
                                                  ''
                                                END               
                                                FROM tbpost p1 WHERE p1.ID = p.id))
                                            WHEN p.postPrivacyType = 2 THEN
                                                FIND_IN_SET({$db->escape($auth['department_id'])},p.postPrivacyIDs)
                                            WHEN p.postPrivacyType = 3 THEN
                                                FIND_IN_SET({$db->escape($auth['position'])},p.postPrivacyIDs)
                                            else
                                                u.company_id={$db->escape($auth['company_id'])}
                                           END
                                            )
                                    OR
				    p.is_active={$db->escape(1)}
				      AND p.post_type={$db->escape(2)}
                                    AND
				    u.id = {$db->escape($auth['id'])} 
                                      ORDER BY date_updated DESC ","array");
                
                foreach ($getPost as $dataP){
                    
                    $path = "images/postUpload";
                    $id_encrypt = md5(md5($dataP['postID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
                        $encodePostImage = array("img"            =>  $postFiles,
                                               "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
						    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                   
                   
                    
                    // LOAD POST DETAILS RETURN
                    $encodePost = array("post"                  =>      $post->returnPost($auth,$getpost,$encodePostImage,$dataP['postID'],$dataP,"query"),
                                        
                                        "uploadedImages"        =>      $encodePostImage);
                    
                    
                    //,'getcomment'=>$encodeComment,'getLike'=>$encodeLike,'getLikeComment'=>$encodeLikeComment
                     
                    $arr[] = array("getpost"            =>      $encodePost,
                                   "getcomment"         =>      $post->loadCommentPost($auth,$dataP['postID'],"","5"),
                                   "getLike"            =>      $post->loadLike($auth,$dataP['postID'],"post"));
                }
                echo functions::view_json_formatter(json_encode($arr));
	    }
    }
}

?>
